package com.agent.auth.service;

import com.agent.auth.dto.AdminLoginRequest;
import com.agent.common.exception.BusinessException;
import com.agent.common.result.ApiResponse;
import com.agent.user.api.feign.AdminUserFeignClient;
import com.agent.user.api.resp.AdminUserResp;
import com.agent.common.exception.AuthenticationException;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 管理员认证服务实现
 * @author Jeff_Wan
 * @description 处理管理员认证核心逻辑
 */
@Service
@RequiredArgsConstructor
public class AdminAuthService {
    private final AdminUserFeignClient adminUserFeignClient;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;
    private final LoginAttemptService loginAttemptService;

    /**
     * 管理员用户登录
     *
     * @param request 请求信息
     * @return token
     */
    public String adminLogin(AdminLoginRequest request) {
        // 检查是否被锁定
        if (loginAttemptService.isBlocked(request.getUsername())) {
            throw new AuthenticationException(ResultCode.ADMIN_ACCOUNT_LOCKED);
        }

        ApiResponse<AdminUserResp> adminUserResult = adminUserFeignClient.getUserByUsername(request.getUsername());

        if (!ApiResponse.isSuccess(adminUserResult)) {
            throw new BusinessException(ResultCode.NORMAL_ERR, "The user service call was unsuccessful");
        }

        AdminUserResp adminUser = adminUserResult.getData();

        if (adminUser == null) {
            loginAttemptService.loginFailed(request.getUsername());
            throw new AuthenticationException(ResultCode.INVALID_CREDENTIALS, "Invalid username or password");
        }

        if (!passwordEncoder.matches(request.getPassword(), adminUser.getPassword())) {
            loginAttemptService.loginFailed(request.getUsername());
            throw new AuthenticationException(ResultCode.INVALID_CREDENTIALS, "Invalid username or password");
        }

        if (adminUser.getStatus() == 0) {
            throw new AuthenticationException(ResultCode.ADMIN_USER_DISABLED);
        }

        // 登录成功，清除失败记录
        loginAttemptService.loginSucceeded(request.getUsername());

        return jwtUtils.generateAdminToken(adminUser.getId(), adminUser.getUsername());
    }
}